package com.example.demo.security.sysGroup.dao;


import com.example.demo.db.BaseDao;
import com.example.demo.security.sysGroup.entity.GroupBean;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class GroupDao extends BaseDao<GroupBean,Integer> {

    @Override
    public String getAddSql() {
        return "INSERT INTO groupChat(groupName,userId) VALUES(:groupName, :userId)";
    }

    public List<GroupBean> queryGroups(Integer userId){
        String sql="SELECT * FROM groupChat WHERE id IN (SELECT groupId FROM groupManagement WHERE state=1 ";
        List<Object> params=new ArrayList<>();
        if (userId!=null){
            sql+="AND userId=? ";
            params.add(userId);
        }
        sql+=" )";
        return getJtl().query(sql,new BeanPropertyRowMapper<GroupBean>(GroupBean.class),params.toArray());
    }

    public GroupBean queryGroupNameById(Integer id){
        String sql="SELECT * FROM groupChat WHERE id=? ";
        return getJtl().queryForObject(sql,new BeanPropertyRowMapper<>(GroupBean.class),id);
    }

    public Integer addGroupMessage(Integer groupId,Integer userId){
        String sql="INSERT INTO groupManagement(groupId,userId,state) VALUES("+groupId+","+userId+",1 )";
        return getJtl().update(sql);
    }

    public Integer delGroupMessage(Integer id,Integer groupId){
        String sql="DELETE FROM groupManagement WHERE userId=? AND groupId=?";
        List<Object> param=new ArrayList<>();
        param.add(id);
        param.add(groupId);
        return getJtl().update(sql,param.toArray());
    }
    public Integer removeInGroup(Integer id,Integer groupId){
        String sql="DELETE FROM groupMessage WHERE userId=? AND groupId=?";
        List<Object> param=new ArrayList<>();
        param.add(id);
        param.add(groupId);
        return getJtl().update(sql,param.toArray());
    }

    public Integer queryPeople(Integer groupId){
        String sql="SELECT COUNT(*) FROM groupManagement WHERE state=1 AND groupId=?";
        return getJtl().queryForObject(sql,new Object[]{groupId},java.lang.Integer.class);
    }
    public void removeGroup(Integer groupId){
        String sql="DELETE FROM groupChat WHERE id=?";
        getJtl().update(sql,groupId);
    }
}
